package com.ytjj.qmyx.supplychain.service;

import com.github.pagehelper.PageHelper;
import com.kuaidi100.sdk.response.ProductCategoryResp;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.constants.SysConfigConstants;
import com.ytjj.qmyx.supplychain.common.enums.ProductCategoryStatusEnums;
import com.ytjj.qmyx.supplychain.common.model.dto.ProductCategoryDto;
import com.ytjj.qmyx.supplychain.common.model.request.ProductCategoryPageListRequest;
import com.ytjj.qmyx.supplychain.common.model.response.ProductCategoryResponse;
import com.ytjj.qmyx.supplychain.common.utils.RedisService;
import com.ytjj.qmyx.supplychain.mapper.entity.YxProductCategory;
import com.ytjj.qmyx.supplychain.mapper.ProductCategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ProductCategoryService {
    @Resource
    private ProductCategoryMapper productCategoryMapper;

    public List<YxProductCategory> selectAll() {
        Example categoryExample = new Example(YxProductCategory.class);
        categoryExample.createCriteria().andEqualTo("status", ProductCategoryStatusEnums.ONLINE.getStatus());
        List<YxProductCategory> categoryList = productCategoryMapper.selectByExample(categoryExample);
        return categoryList;
    }

    public List<YxProductCategory> getBottomCategoryList(Integer id) {
        Example example = new Example(YxProductCategory.class);
        example.createCriteria().andEqualTo("pid", id).andEqualTo("status", ProductCategoryStatusEnums.ONLINE.getStatus());
        List<YxProductCategory> list = productCategoryMapper.selectByExample(example);
        return list;
    }

    public List<YxProductCategory> getList(Integer pid) {
        Example example = new Example(YxProductCategory.class);
        example.createCriteria().andEqualTo("pid", pid);
        List<YxProductCategory> list = productCategoryMapper.selectByExample(example);
        return list;
    }

    public List<YxProductCategory> queryByTitle(String title) {
        Example example = new Example(YxProductCategory.class);
        example.createCriteria().andLike("title", "%" + title + "%").andEqualTo("status", ProductCategoryStatusEnums.ONLINE.getStatus());
        List<YxProductCategory> list = productCategoryMapper.selectByExample(example);
        return list;
    }

    public YxProductCategory queryById(Integer id) {
        YxProductCategory result = productCategoryMapper.selectByPrimaryKey(id);
        return result;
    }

    public CommonPage<YxProductCategory> list(ProductCategoryPageListRequest productCategoryRequest) {
        Example example = new Example(YxProductCategory.class);
        Example.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(productCategoryRequest.getTitle())) {
            criteria.andLike("title", "%" + productCategoryRequest.getTitle() + "%");
        }
        if (null != productCategoryRequest.getStatus()) {
            criteria.andEqualTo("status", productCategoryRequest.getStatus());
        }
        if (null != productCategoryRequest.getPid()) {
            criteria.andEqualTo("pid", productCategoryRequest.getPid());
        }
        if (null != productCategoryRequest.getId()) {
            criteria.andEqualTo("pid", productCategoryRequest.getId());
        }
        if (null == productCategoryRequest.getId() && null == productCategoryRequest.getPid()) {
            criteria.andEqualTo("pid", 0);
        }
        example.orderBy("pid").asc().orderBy("createTime").desc();
        PageHelper.startPage(productCategoryRequest.getPageNum(),productCategoryRequest.getPageSize());
        List<YxProductCategory> productCategorys = productCategoryMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(productCategorys)){
            for(YxProductCategory productCategory: productCategorys){
                if(productCategory.getPid() != 0){
                    YxProductCategory pc = productCategoryMapper.selectByPrimaryKey(productCategory.getPid());
                    productCategory.setPTitle(pc.getTitle());
                }
            }
        }
        return CommonPage.restPage(productCategorys);
    }

    public int create(YxProductCategory productCategory) {
        // 如果没有选择父id 则默认为1级分类 “0”
        if(productCategory.getPid() == null){
            productCategory.setPid(0);
        }
        // 默认下架
        if (productCategory.getStatus() == null){
            productCategory.setStatus(SysConfigConstants.Category_Type.TYPE_2);
        }
        productCategory.setId(null);
        productCategory.setCreateTime(new Date());
        return productCategoryMapper.insertSelective(productCategory);
    }

    public int update(YxProductCategory productCategory) {
        //如果Pid为0或者为空,则为一级分类
        if (!StringUtils.isEmpty(productCategory.getPid()) && productCategory.getPid() != 0) {
            //如果该分类状态改为上架,先查看上级分类是否是上架
        }

        // 如果没有选择父id 则默认为1级分类 “0”
        if (productCategory.getPid() == null) {
            productCategory.setPid(0);
        }
        productCategory.setUpdateTime(new Date());
        return productCategoryMapper.updateByPrimaryKeySelective(productCategory);
    }

    public int delete(Integer id) {
        return productCategoryMapper.deleteByPrimaryKey(id);
    }

    public List<Map<String, Object>> getSpecListByCategoryId(Integer categoryId) {
        // 根据商品属性id集合获取规格List
        List<Map<String,Object>> spec_array = this.getSpecListByAttributeKeyIds(categoryId);
        return spec_array;
    }

    /**
     * 根据商品分类id获取规格List
     * @param productCategoryId
     * @return
     */
    private List<Map<String,Object>> getSpecListByAttributeKeyIds(Integer productCategoryId){
        List<Map<String,Object>> spec_array = new ArrayList<>();

//        ProductAttributeKeyExample productAttributeKeyExample = new ProductAttributeKeyExample();
//        productAttributeKeyExample.createCriteria().andCategoryIdEqualTo(productCategoryId);
//        List<ProductAttributeKey> productAttributeKeys = productAttributeKeyMapper.selectByExample(productAttributeKeyExample);
//        List<Integer> attributeKeyIds = productAttributeKeys.stream().map(ProductAttributeKey::getId).collect(Collectors.toList());
//        if(!CollectionUtils.isEmpty(attributeKeyIds)){
//            for(Integer attributeKeyId : attributeKeyIds){
//                Map<String,Object> spec_map = new LinkedHashMap<>();
//                Map<String,Object> spanKeys_map = new LinkedHashMap<>();
//                ProductAttributeKey productAttributeKey = productAttributeKeyMapper.selectByPrimaryKey(attributeKeyId);
//                ProductAttributeValueExample productAttributeValueExample = new ProductAttributeValueExample();
//                productAttributeValueExample.createCriteria().andAttributeIdEqualTo(productAttributeKey.getId());
//                List<ProductAttributeValue> productAttributeValues = productAttributeValueMapper.selectByExample(productAttributeValueExample);
//                spanKeys_map.put("id","p"+productAttributeKey.getId());
//                spanKeys_map.put("name",productAttributeKey.getAttributeName());
//                spec_map.put("spanName",spanKeys_map);
//                if(!CollectionUtils.isEmpty(productAttributeValues)){
//                    List<Map<String,Object>> spanValues = new ArrayList<>();
//                    for(ProductAttributeValue productAttributeValue : productAttributeValues){
//                        Map<String,Object> spanValues_map = new HashMap<>();
//                        spanValues_map.put("id", productAttributeValue.getId());
//                        spanValues_map.put("name",productAttributeValue.getAttributeValue());
//                        spanValues.add(spanValues_map);
//                    }
//                    spec_map.put("spanValue",spanValues);
//                }
//                spec_array.add(spec_map);
//            }
//        }
        return spec_array;
    }

    public List<ProductCategoryResp> getProductCategoryResps(List<ProductCategoryResp> list) {
        List<ProductCategoryResp> categoryDTOList = new ArrayList<>();
        //查询所有父类目录
        for(ProductCategoryResp categoryEntity : list) {
            if(categoryEntity.getPid() == 0) {
                categoryDTOList.add(categoryEntity);
            }
        }
        //查询子目录
        findSubCategory(categoryDTOList,list);

        return categoryDTOList;
    }


    /**
     * 查询子目录
     * @param categoryDTOList
     * @param categoryEntityList
     */
    private void findSubCategory(List<ProductCategoryResp> categoryDTOList, List<ProductCategoryResp> categoryEntityList) {
        //遍历所有父类分类
        for(ProductCategoryResp categoryDTO : categoryDTOList) {
            List<ProductCategoryResp> subCategoryVoList = new ArrayList<>();
            //遍历父类下的cat_id与子类parent_cid相匹配的分类
            for(ProductCategoryResp category : categoryEntityList) {
                if(categoryDTO.getId().equals(category.getPid())) {
                    subCategoryVoList.add(category);
                }
                //设置subCategories
                categoryDTO.setChildProductCategory(subCategoryVoList);
            }
            //递归调用
            findSubCategory(subCategoryVoList, categoryEntityList);
        }
    }

    /**
     * 根据第三级分类id获取全部分类id
     * @param bottomCategoryIds
     * @return
     */
    public List<ProductCategoryDto> getCategoryIdByBottomCategoryIds(List<Integer> bottomCategoryIds) {
        return productCategoryMapper.getCategoryIdByBottomCategoryId(bottomCategoryIds);
    }
}
